<?php
class ProductCacheService
{
	public function __construct()
	{
		
	}
	
	public function getGroupList()
	{
		$cacheCfg	= C('LtConfig')->get('cache.product');
		$listDir	= $cacheCfg['listdir'];
		$detailDir	= $cacheCfg['detaildir'];
		
		$listDirs	= C('CommonFunction')->getDirFiles($listDir);
		$detailDirs	= C('CommonFunction')->getDirFiles($detailDir);
		
		$dirs		= array();
		foreach($listDirs as $d)
		{
			if($d=='.' || $d=='..')
			{
				continue;
			}
			if(!in_array($d,$dirs))
			{
				$dirs[]	= $d;
			}
		}
		foreach($detailDirs as $d)
		{
			if($d=='.' || $d=='..')
			{
				continue;
			}
			if(!in_array($d,$dirs))
			{
				$dirs[]	= $d;
			}
		}
		
		return $dirs;
	}
	
	public function deleteByDate($date)
	{
		if(empty($date) || !is_numeric($date))
		{
			return 0;
		}
		
		$cacheCfg	= C('LtConfig')->get('cache.product');
		$listDir	= $cacheCfg['listdir'];
		$detailDir	= $cacheCfg['detaildir'];
		
		if($date==date('Ymd'))
		{
			//删除当天的缓存，关闭缓存写入
			if($cacheCfg['listcacheenable']==1 || $cacheCfg['detailcacheenable']==1)
			{
				//关闭缓存功能
				$this->disableCache();
			}
		}
		
		//清空列表
		$num = $this->clearCache($listDir.$date.DIRECTORY_SEPARATOR,0);
		if($num<500)
		{
			//清空详情
			$num = $this->clearCache($detailDir.$date.DIRECTORY_SEPARATOR,$num);
		}
		
		if($num<500)
		{
			//清空数据库
			for($i=1;$i<=10;$i++)
			{
				$dao	= new ProductCacheDao($i);
				$condition['expression']			= 'created=:created';
				$condition['value']['created']		= $date;
				$dao->deleteRows($condition);
			}
			
			$cf = C('CommonFunction');
			$cf->rmdir($listDir.$date);
			$cf->rmdir($detailDir.$date);
		}
		
		return $num;
	}
	
	public function deleteAll()
	{
		$config = C('LtConfig');
		$cacheCfg	= $config->get('cache.product');
		if($cacheCfg['listcacheenable']==1 || $cacheCfg['detailcacheenable']==1)
		{
			//关闭缓存功能
			$this->disableCache();
		}
		
		$listDir	= $cacheCfg['listdir'];
		$detailDir	= $cacheCfg['detaildir'];
		
		//清空列表
		$num = $this->clearCache($listDir,0);
		if($num<500)
		{
			//清空详情
			$num = $this->clearCache($detailDir,$num);
		}
		
		if($num<500)
		{
			//清空数据库
			for($i=1;$i<=10;$i++)
			{
				$dao	= new ProductCacheDao($i);
				$dao->deleteRows(array());
			}
			
			$cf = C('CommonFunction');
			$cf->rmdir($listDir);
			$cf->rmdir($detailDir);
		}
		
		return $num;
	}
	
	private function clearCache($dir,$num)
	{
		if (!file_exists($dir))
		{
			return 0;
		}
		
		$dh  = opendir($dir);
		while (false !== ($filename = readdir($dh))) 
		{
			if($filename=='.' || $filename=='..')
			{
				continue;
			}
			
			$file = $dir.DIRECTORY_SEPARATOR.$filename;
		    if(is_file($file))
		    {
		    	@unlink($file);
		    	$num++;
		    	if($num>=500)
		    	{
		    		break;
		    	}
		    }
		    else
		    {
		    	$num = $this->clearCache($file,$num);
		    	if($num>=500)
		    	{
		    		break;
		    	}
		    }
		}
		closedir($dh);
		
		return $num;
	}
	
	private function disableCache()
	{
		$confBaseDir	= substr(dirname(__FILE__), 0, strrpos(__FILE__, "lib")).'conf/standard/';
		$cacheFile		= $confBaseDir.'cache.conf.php';
		
		$content = file_get_contents($cacheFile);
		
		$lce = 0;
		$dce = 0;
		
		$content 	= preg_replace('~\$config\["cache.product"\]\["listcacheenable"\].*?=.*?"(.*?)"~is', '$config["cache.product"]["listcacheenable"] = "'.str_replace('"',"'",$lce).'"', $content);
		$content 	= preg_replace('~\$config\["cache.product"\]\["detailcacheenable"\].*?=.*?"(.*?)"~is', '$config["cache.product"]["detailcacheenable"] = "'.str_replace('"',"'",$dce).'"', $content);
		
		$length = file_put_contents($cacheFile, $content);
		return $length>0;
	}
	
	public function getSizeByDate($d)
	{
		if(empty($d) || !is_numeric($d))
		{
			return 0;
		}
		$cacheCfg	= C('LtConfig')->get('cache.product');
		$listDir	= $cacheCfg['listdir'];
		$detailDir	= $cacheCfg['detaildir'];
		
		$cache 	= new LtCache();
		$cache->init();
		$ch 	= $cache->getTDG("cache_size");
		
		$listSize	= -1;
		$detailSize	= -1;
		$update	= false;
		$tmp	= $ch->get('data');
		if($tmp!==false)
		{
			if(array_key_exists($d, $tmp))
			{
				if(array_key_exists('detail',$tmp[$d]))
				{
					$lastModify = filemtime($detailDir.$d);
					$cacheTime	= $tmp[$d]['detail']['time'];
					if($lastModify<=$cacheTime)
					{
						$detailSize	= $tmp[$d]['detail']['size'];
					}
				}
				if(array_key_exists('list',$tmp[$d]))
				{
					$lastModify = filemtime($listDir.$d);
					$cacheTime	= $tmp[$d]['list']['time'];
					if($lastModify<=$cacheTime)
					{
						$listSize	= $tmp[$d]['list']['size'];
					}
				}
			}
			$update	= true;
		}
		
		if(!$update)
		{
			$tmp	= array();
		}
		
		if($detailSize==-1)
		{
			$detailSize	= C('CommonFunction')->countDirSize($detailDir.$d);
			if($detailSize<0)
			{
				$detailSize	= 0;
			}
			$tmp[$d]['detail']	= array('size'=>$detailSize,'time'=>time());
		}
		if($listSize==-1)
		{
			$listSize	= C('CommonFunction')->countDirSize($listDir.$d);
			if($listSize<0)
			{
				$listSize	= 0;
			}
			$tmp[$d]['list']	= array('size'=>$listSize,'time'=>time());
		}
		
		if($update)
		{
			$ch->update('data',$tmp,86400*365);
		}
		else
		{
			$ch->add('data',$tmp,86400*365);
		}
		
		return $detailSize + $listSize;
	}
	
	public function updateCacheSize()
	{
		$list		= $this->getGroupList();
		if(!$list)
		{
			$list	= array();
		}
		
		$cache 	= new LtCache();
		$cache->init();
		$ch 	= $cache->getTDG("cache_size");
		$tmp	= $ch->get('data');
		if(!$tmp)
		{
			return;
		}
		$update	= false;
		foreach($tmp as $k=>$v)
		{
			if(!in_array($k,$list))
			{
				unset($tmp[$k]);
				$update	= true;
			}
		}
		if(!$tmp)
		{
			$tmp	= array();
		}
		if($update)
		{
			$ch->update('data',$tmp,86400*365);
		}
	}
}
?>